package com.simpou.commons.utils.file;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;


/**
 * Operações úteis sobre o framework Apache Velocity.
 *
 * @author Jonas Pereira
 * @since 2011-08-22
 * @version 2011-10-19
 */
public final class VelocityHelper {
    /**
     * Velocity engine.
     */
    private static final VelocityEngine ENGINE;

    static {
        ENGINE = new VelocityEngine();
        ENGINE.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ENGINE.setProperty("classpath.resource.loader.class",
            ClasspathResourceLoader.class.getName());

        try {
            ENGINE.init();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Velocity context.
     */
    private VelocityContext context;

    /**
     * Velocity template.
     */
    private Template template;

    /**
     * <p>Constructor for VelocityHelper.</p>
     *
     * @param fileName Caminho completo do arquivo template.
     * @throws java.lang.Exception Erros ao processar template.
     */
    public VelocityHelper(final String fileName) throws Exception {
        this.context = new VelocityContext();
        this.template = ENGINE.getTemplate(fileName);
    }

    /**
     * Adiciona parâmetros a serem substituídos nos templates.
     *
     * @param param Parâmetro.
     * @param value Valor.
     */
    public void setParameter(final String param, final Object value) {
        context.put(param, value);
    }

    /**
     * <p>merge.</p>
     *
     * @return Arquivo template substituído pelos valores dos parâmetros.
     * @throws java.lang.Exception Erros ao processar template.
     */
    public String merge() throws Exception {
        StringWriter writer = new StringWriter();
        template.merge(context, writer);

        return writer.toString();
    }
}
